package cn.maihe.elg.operation.centers.guogu.handler.service;

import cn.maihe.elg.operation.centers.guogu.config.GuoGuCenterInfosConfig;
import cn.maihe.elg.operation.centers.guogu.dto.GuoGuBaseRespDTO;
import cn.maihe.elg.operation.centers.guogu.dto.handler.req.GuoGuInvoiceApplyReq;
import cn.maihe.elg.operation.centers.guogu.handler.GuoGuCenterTradeService;
import cn.maihe.elg.operation.centers.supports.CenterTradeContext;
import cn.maihe.elg.operation.centers.supports.annotation.CenterTradeService;
import cn.maihe.elg.operation.model.enums.AcceptOrderStatus;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.CenterProviderEnum;
import cn.maihe.elg.operation.model.enums.InvoiceFlagEnum;
import cn.maihe.elg.operation.model.enums.InvoiceLineEnum;
import cn.maihe.elg.operation.model.enums.InvoiceStatusEnum;
import cn.maihe.elg.operation.model.enums.TradeType;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.InvoiceInfoDO;
import cn.maihe.elg.operation.service.invoice.InvoiceInfoService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.ApplyOrderInfoService;
import cn.maihe.elg.operation.supports.invoice.nuonuo.InvoiceHelper;
import cn.maihe.elg.operation.utils.CreateGuaranteeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;

/**
 * @Description 发票申请推送
 * @Author SSX
 * @Date 2025/03/18
 */
@CenterTradeService(
        provider = CenterProviderEnum.GUOGU,
        centerNo = CenterNoEnum.GUOGU,
        tradeType = TradeType.invoice_apply,
        reqClass = GuoGuInvoiceApplyReq.class,
        respClass = GuoGuBaseRespDTO.class
)
@Slf4j
public class GuoGuInvoiceApplyService extends GuoGuCenterTradeService<GuoGuInvoiceApplyReq, GuoGuBaseRespDTO> {
    public GuoGuInvoiceApplyService(GuoGuCenterInfosConfig centerInfosConfig) {
        super(centerInfosConfig);
    }

    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private ApplyOrderInfoService applyOrderInfoService;
    @Resource
    private InvoiceHelper invoiceHelper;
    @Resource
    private InvoiceInfoService invoiceInfoService;

    @Override
    protected void verifyParam(CenterTradeContext<GuoGuInvoiceApplyReq, GuoGuBaseRespDTO> context) {
//        super.verifyParam(context);
//        GuoGuProjectAbnormalApplyReq req = context.getReq();
//        String orderNo = req.getApplyno();
//        boolean exists = acceptOrderInfoService.existsCenterOrderId(context.getCenterId(), orderNo);
//        Assert.isTrue(!exists, () -> "中心订单编号已存在");
    }

    @Override
    public GuoGuBaseRespDTO processService(CenterTradeContext<GuoGuInvoiceApplyReq, GuoGuBaseRespDTO> context) {
        GuoGuInvoiceApplyReq req = context.getReq();

        AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.getByCenterOrderId(context.getCenterId(),context.getOrgId(),req.getApplyno());

        String invoiceLine = "0".equals(req.getInvoiceType())?InvoiceLineEnum.BS.getInvoiceLineCode():
                InvoiceLineEnum.PC.getInvoiceLineCode();
        if(CreateGuaranteeUtil.isSuiXingByClientId(acceptOrderInfoDO.getClientId())){
            log.info("GuoGuInvoiceApplyService clientId:{}",acceptOrderInfoDO.getClientId());
            AcceptOrderInfoDO updateAcceptOrder = AcceptOrderInfoDO.builder().id(acceptOrderInfoDO.getId()).build();
            updateAcceptOrder.setInvoiceLine(invoiceLine);
            acceptOrderInfoService.updateById(updateAcceptOrder);
            return GuoGuBaseRespDTO.success("开票受理成功");
        }

        if (acceptOrderInfoDO.getStatus() != AcceptOrderStatus.HAS_OUT_GUARANTEE.getStatus()) {
            return GuoGuBaseRespDTO.error("未出函，不能开发票");
        }

        InvoiceInfoDO invoiceInfoDO = null;

        //未开票则发起开票申请
        if (acceptOrderInfoDO.getInvoiceFlag() == null || acceptOrderInfoDO.getInvoiceFlag() == InvoiceFlagEnum.INVOICEPRE.getValue()) {
            invoiceInfoDO = applyOrderInfoService.invoice(acceptOrderInfoDO, false,invoiceLine);
        } else {
            //已开票或开票中
            invoiceInfoDO = invoiceInfoService.selectById(acceptOrderInfoDO.getInvoiceId());
        }

        if (invoiceInfoDO == null) {
            throw new RuntimeException("查无开票记录，请先开票申请后再试");
        }

        if (1 == invoiceInfoDO.getInvoiceMode() && invoiceInfoDO.getStatus() != InvoiceStatusEnum.INVOICED.getValue()) {
            invoiceInfoDO = invoiceHelper.queryInvoiceResultAndDownload(invoiceInfoDO);
        }

        if (StringUtils.isBlank(invoiceInfoDO.getInvoiceNo()) ||
                invoiceInfoDO.getStatus() != InvoiceStatusEnum.INVOICED.getValue()) {
            throw new RuntimeException("当前开票状态为[" + InvoiceStatusEnum.getLabel(invoiceInfoDO.getStatus()) + "]稍后再试");
        }

        // 开票成功通知国谷
        invoiceHelper.invoiceResultNotify(acceptOrderInfoDO.getAcceptOrderNo());
        return GuoGuBaseRespDTO.success("开票成功");

    }

}
